<template>
  <div id="manageQuestionView">
    <!-- 题目列表 -->
    <a-card class="table-card" :bordered="true">
      <template #title>
        <div class="card-title">
          <icon-file />
          <span>题目列表</span>
        </div>
      </template>

      <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :loading="tableLoading"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
          position: ['bottomCenter'],
        }"
        :row-class-name="
          (_record: any, index: number) => (index % 2 === 0 ? 'even-row' : 'odd-row')
        "
        @page-change="onPageChange"
      >
        <template #content="{ record }">
          <a-tooltip :content="record.content">
            <div class="ellipsed-column">{{ record.content }}</div>
          </a-tooltip>
        </template>

        <template #tags="{ record }">
          <a-popover position="right">
            <template #content>
              <div class="tags-container">
                <a-tag
                  v-for="tag in parseJsonField(record.tags)"
                  :key="tag"
                  :color="getTagColor(tag)"
                  class="tag-item"
                >
                  {{ tag }}
                </a-tag>
              </div>
            </template>
            <a-tag color="blue" style="cursor: pointer">
              {{ parseJsonField(record.tags).length }} 个标签
            </a-tag>
          </a-popover>
        </template>

        <template #createTime="{ record }">
          <div class="table-cell">
            {{ moment(record.createTime).format("YYYY-MM-DD") }}
          </div>
        </template>

        <template #judgeCase="{ record }">
          <a-collapse>
            <a-collapse-item header="查看用例" class="test-case-collapse">
              <div class="test-case">
                <div
                  v-for="(testCase, index) in parseTestCases(record.judgeCase)"
                  :key="index"
                  class="test-case-item"
                >
                  <span><b>输入:</b></span>
                  <pre class="inline">{{ formatTestCase(testCase.input) }}</pre>
                  <br />
                  <span><b>输出:</b></span>
                  <pre class="inline">{{ testCase.output }}</pre>
                </div>
              </div>
            </a-collapse-item>
          </a-collapse>
        </template>

        <template #optional="{ record }">
          <a-space>
            <a-button type="primary" size="small" @click="doUpdate(record)">
              <template #icon><icon-edit /></template>
              修改
            </a-button>
            <a-popconfirm
              content="确定删除此题目吗？"
              @ok="() => doDelete(record)"
            >
              <a-button status="danger" size="small">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>

        <template #empty>
          <div class="empty-state">
            <icon-empty />
            <p>暂无题目数据</p>
            <a-button type="primary" @click="router.push('/add/question')">
              添加题目
            </a-button>
          </div>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import { Question, QuestionControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";
import {
  IconFile,
  IconEdit,
  IconDelete,
  IconEmpty,
} from "@arco-design/web-vue/es/icon";

const tableRef = ref();
const dataList = ref([]);
const total = ref(0);
const searchParams = ref({ pageSize: 10, current: 1 });
const tableLoading = ref(false);
const router = useRouter();

const loadData = async () => {
  tableLoading.value = true;
  try {
    const res = await QuestionControllerService.listQuestionByPageUsingPost(
      searchParams.value
    );
    if (res.code === 0) {
      dataList.value = res.data.records;
      total.value = res.data.total;
    } else {
      message.error("加载失败，" + res.message);
    }
  } catch (error) {
    message.error("请求失败，请检查网络");
  } finally {
    tableLoading.value = false;
  }
};

watchEffect(() => {
  loadData();
});

onMounted(() => {
  loadData();
});

const columns = [
  { title: "标题", dataIndex: "title" },
  { title: "内容", slotName: "content" },
  { title: "标签", slotName: "tags", align: "center" },
  { title: "提交数", dataIndex: "submitNum", align: "center" },
  { title: "通过数", dataIndex: "acceptedNum", align: "center" },
  { title: "判题用例", slotName: "judgeCase", align: "center" },
  { title: "创建时间", slotName: "createTime" },
  { title: "操作", slotName: "optional", align: "center", width: 160 },
];

const onPageChange = (page: number) => {
  searchParams.value = { ...searchParams.value, current: page };
};

const doDelete = async (question: Question) => {
  try {
    // 修正方法名为 deleteQuestionUsingPost1
    const res = await QuestionControllerService.deleteQuestionUsingPost1({
      id: question.id,
    });
    if (res.code === 0) {
      message.success("删除成功");
      loadData();
    } else {
      message.error("删除失败，" + res.message);
    }
  } catch (error) {
    message.error("请求失败，请检查网络");
  }
};

const doUpdate = (question: Question) => {
  router.push({ path: "/update/question", query: { id: question.id } });
};

// 解析 JSON 格式的测试用例
const parseTestCases = (judgeCase: string) => {
  try {
    return JSON.parse(judgeCase);
  } catch (e) {
    return [];
  }
};

// 通用 JSON 字段解析函数
const parseJsonField = (field: string) => {
  try {
    return JSON.parse(field);
  } catch (e) {
    return [];
  }
};

const formatTestCase = (input: string) => {
  return input
    .split(", ")
    .map((line) => line.trim())
    .join("\n");
};

const getTagColor = (tag: string) => {
  const colors = ["green", "blue", "red", "orange", "purple"];
  const index = tag.charCodeAt(0) % colors.length;
  return colors[index];
};
</script>

<style scoped>
#manageQuestionView {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #165dff;
  font-weight: 500;
}

.switch-card,
.table-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 统一开关的外层容器 */
.switch-container {
  display: flex;
  gap: 50px; /* 调整开关间距 */
  padding: 16px 0;
}

/* 开关单元 */
.switch-item {
  display: flex;
  gap: 12px;
  padding: 10px 16px;
  background: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 圆形图标 */
.switch-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* 文字标签 */
.switch-label {
  font-size: 14px;
  color: #333;
}

/* 表格内容 */
.ellipsed-column {
  width: 180px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

/* 行样式 */
:deep(.even-row) {
  background-color: #f9f9f9;
}

:deep(.odd-row) {
  background-color: #ffffff;
}

/* 标签容器 */
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-width: 300px;
}

/* 标签样式 */
.tag-item {
  margin-right: 0;
}

/* 判题用例折叠框 */
.test-case-collapse {
  background-color: #f6f8fa;
  border-radius: 5px;
  margin-bottom: 8px;
}

/* 判题用例样式 */
.test-case-item {
  margin-bottom: 8px;
  background: #ffffff;
  padding: 8px;
  border-radius: 5px;
  border: 1px solid #e8e8e8;
}

/* 代码块格式 */
.inline {
  display: inline;
  white-space: pre-wrap;
  font-family: "Courier New", monospace;
  background-color: #f5f5f5;
  padding: 2px 4px;
  border-radius: 3px;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #86909c;
}

.empty-state :deep(svg) {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c2c7d0;
}

.empty-state p {
  margin-bottom: 16px;
}
</style>
